package com.adan.auditlog;

import com.adan.auditlog.handler.IAuditHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Aspect
@Component
public class SqlAspect {
	@Autowired
	private List<IAuditHandler> auditHandleList;

	@Pointcut("execution(int com.baomidou.mybatisplus.core.mapper.BaseMapper.deleteById(..))" +
				"|| execution(int com.baomidou.mybatisplus.core.mapper.BaseMapper.insert(..))" +
				"|| execution(int com.baomidou.mybatisplus.core.mapper.BaseMapper.updateById(..))")
	private void mapper() {
	}

	/**
	 * 记录表的操作日志,insert,update,delete(逻辑删除)
	 *
	 * @param joinPoint
	 */
	@Around("mapper()")
	public Object recordOperate(ProceedingJoinPoint joinPoint) throws Throwable {
		for (IAuditHandler handle : auditHandleList) {
			Object res = handle.exec(joinPoint);
			if (Objects.nonNull(res)) {
				return res;
			}
		}
		return joinPoint.proceed();
	}
}
